from sqlalchemy.ext.asyncio import AsyncSession
from typing import List
from config.constant import CommonConstant
from exceptions.exception import ServiceException
from module_admin.entity.vo.common_vo import CrudResponseModel
from module_statistics.dao.plant_service_dao import PlantServiceDao
from module_statistics.entity.vo.plant_service_vo import DeletePlantServiceModel, PlantServiceModel, PlantServicePageQueryModel
from utils.common_util import CamelCaseUtil
from utils.excel_util import ExcelUtil


class PlantServiceService:
    """
    种植主体服务统计模块服务层
    """

    @classmethod
    async def get_plant_service_list_services(
        cls, query_db: AsyncSession, query_object: PlantServicePageQueryModel, is_page: bool = False
    ):
        """
        获取种植主体服务统计列表信息service

        :param query_db: orm对象
        :param query_object: 查询参数对象
        :param is_page: 是否开启分页
        :return: 种植主体服务统计列表信息对象
        """
        plant_service_list_result = await PlantServiceDao.get_plant_service_list(query_db, query_object, is_page)

        return plant_service_list_result


    @classmethod
    async def get_planter_service_summary_service(cls, query_db: AsyncSession, query_object: PlantServicePageQueryModel):
        """
        :param query_db:
        :param query_object:
        :return:
        """
        planter_service_summary_result = await PlantServiceDao.get_planter_service_summary_list(query_db, query_object)

        return planter_service_summary_result

    @classmethod
    async def get_service_type_summary_service(cls, query_db: AsyncSession, query_object: PlantServicePageQueryModel):
        service_type_summary_result = await PlantServiceDao.get_service_type_summary_list(query_db, query_object)
        return service_type_summary_result

    @classmethod
    async def get_service_monthly_summary_service(cls, query_db: AsyncSession, query_object: PlantServicePageQueryModel):
        service_monthly_summary_result = await PlantServiceDao.get_service_monthly_summary_service(query_db, query_object)
        return service_monthly_summary_result

    @classmethod
    async def add_plant_service_services(cls, query_db: AsyncSession, page_object: PlantServiceModel):
        """
        新增种植主体服务统计信息service

        :param query_db: orm对象
        :param page_object: 新增种植主体服务统计对象
        :return: 新增种植主体服务统计校验结果
        """
        try:
            await PlantServiceDao.add_plant_service_dao(query_db, page_object)
            await query_db.commit()
            return CrudResponseModel(is_success=True, message='新增成功')
        except Exception as e:
            await query_db.rollback()
            raise e

    @classmethod
    async def edit_plant_service_services(cls, query_db: AsyncSession, page_object: PlantServiceModel):
        """
        编辑种植主体服务统计信息service

        :param query_db: orm对象
        :param page_object: 编辑种植主体服务统计对象
        :return: 编辑种植主体服务统计校验结果
        """
        edit_plant_service = page_object.model_dump(exclude_unset=True, exclude={})
        plant_service_info = await cls.plant_service_detail_services(query_db, page_object.id)
        if plant_service_info.id:
            try:
                await PlantServiceDao.edit_plant_service_dao(query_db, edit_plant_service)
                await query_db.commit()
                return CrudResponseModel(is_success=True, message='更新成功')
            except Exception as e:
                await query_db.rollback()
                raise e
        else:
            raise ServiceException(message='种植主体服务统计不存在')

    @classmethod
    async def delete_plant_service_services(cls, query_db: AsyncSession, page_object: DeletePlantServiceModel):
        """
        删除种植主体服务统计信息service

        :param query_db: orm对象
        :param page_object: 删除种植主体服务统计对象
        :return: 删除种植主体服务统计校验结果
        """
        if page_object.ids:
            id_list = page_object.ids.split(',')
            try:
                for id in id_list:
                    await PlantServiceDao.delete_plant_service_dao(query_db, PlantServiceModel(id=id))
                await query_db.commit()
                return CrudResponseModel(is_success=True, message='删除成功')
            except Exception as e:
                await query_db.rollback()
                raise e
        else:
            raise ServiceException(message='传入记录id为空')

    @classmethod
    async def plant_service_detail_services(cls, query_db: AsyncSession, id: int):
        """
        获取种植主体服务统计详细信息service

        :param query_db: orm对象
        :param id: 记录id
        :return: 记录id对应的信息
        """
        plant_service = await PlantServiceDao.get_plant_service_detail_by_id(query_db, id=id)
        if plant_service:
            result = PlantServiceModel(**CamelCaseUtil.transform_result(plant_service))
        else:
            result = PlantServiceModel(**dict())

        return result

    @staticmethod
    async def export_plant_service_list_services(plant_service_list: List):
        """
        导出种植主体服务统计信息service

        :param plant_service_list: 种植主体服务统计信息列表
        :return: 种植主体服务统计信息对应excel的二进制数据
        """
        # 创建一个映射字典，将英文键映射到中文键
        mapping_dict = {
            'id': '记录id',
            'year': '数据统计年份',
            'planterId': '种植主体id',
            'serviceMonth': '服务月份',
            'serviceType': '服务类型',
            'serviceCount': '服务次数',
        }
        binary_data = ExcelUtil.export_list2excel(plant_service_list, mapping_dict)

        return binary_data
